//
//  ViewController.m
//  CoreAnimation动画之CADisplayLink
//
//  Created by zxy on 2018/4/27.
//  Copyright © 2018年 zssh. All rights reserved.
//

#import "ViewController.h"

#define CUREENT_SYSTEMVERSION ([[[UIDevice currentDevice]systemVersion] floatValue])

@interface ViewController (){
    NSInteger _currentIndex;
}
@property(nonatomic,strong)CADisplayLink *timerInc;
@property (weak, nonatomic) IBOutlet UIImageView *imgV;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /*OC中的三种定时器：CADisplayLink、NSTimer、GCD，CADisplayLink优势就在于他的执行频率是根据设备屏幕的刷新频率来计算的。换句话讲，他也是时间间隔最准确的定时器*/
    
    self.view.backgroundColor = [UIColor grayColor];
    ///target selector 模式初始化一个实例
    self.timerInc = [CADisplayLink displayLinkWithTarget:self selector:@selector(changImg)];
    //暂停
    self.timerInc.paused = YES;
    ///selector触发间隔
    if(CUREENT_SYSTEMVERSION < 10.0){
        self.timerInc.frameInterval = 2;
    }else{
        //默认初始值是60，越大动画速度越快,模拟器有点卡
        self.timerInc.preferredFramesPerSecond = 30;
    }
    CAKeyframeAnimation
    ///加入一个runLoop
    [self.timerInc addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}


#pragma mark -每2s改变图片
-(void)changImg{
    _currentIndex++;
    if(_currentIndex > 75){
        _currentIndex = 1;
    }
    self.imgV.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",_currentIndex]];
}
#pragma mark -控制动画启动和停止
- (IBAction)CADisplayLink:(UIButton *)sender {
    self.timerInc.paused = !self.timerInc.paused;
}


-(void)dealloc{
    [self.timerInc invalidate];
    self.timerInc = NULL;
}

@end
